package pl.cezary.butler.walili.common.config;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Cezary Butler
 */
public class Configuration {

    private static final Logger log = Logger.getLogger(Configuration.class.getName());    
    private final File CONFIG = new File("./runtime/config.properties");
    private final Properties def;
    protected Properties prop;
    
    private String getDefConfig(){
        return getClass().getPackage().getName().replace('.', '/') + "/" + "config.properties";
    }

    protected Configuration() {
        def = new Properties();
        try {
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(getDefConfig());
            def.load(is);
        } catch (FileNotFoundException ex) {
            log.log(Level.SEVERE, "Default configuration not found", ex);
            throw new RuntimeException("Default configuration not found", ex);
        } catch (IOException ex) {
            log.log(Level.SEVERE, "Problem during reading default configuration", ex);
            throw new RuntimeException("Problem during reading default configuration", ex);
        }
        refreshConfig();
    }
    
    protected void clearFetched(){
        
    }
    
    protected void readFrom(File input) {
        clearFetched();
        prop = new Properties(def);
        try {
            prop.load(new FileReader(input));
        } catch (FileNotFoundException ex) {
            log.log(Level.INFO, "No user configuration");
        } catch (IOException ex) {
            log.log(Level.WARNING, "Problem during reading user configuration", ex);
        }
    }
    
    public final void refreshConfig() {
        readFrom(CONFIG);
    }
}
